//
//  M1HomeViewController.m
//  NewMarryU
//
//  Created by apple on 2018/7/11.
//  Copyright © 2018年 Cedar. All rights reserved.
//

#import "M1HomeViewController.h"
#import "M1DragContainer.h"
#import "M1CustomCardView.h"
#import "M1HomeDetailsVC.h"
#import "M1FiltrateVC.h"
#import "M1HomeModel.h"
#import "M1PhotoGalleryVC.h"
#import "M1PersonalDataVC.h"
@interface M1HomeViewController ()<CCDraggableContainerDataSource,CCDraggableContainerDelegate
>
{
    NSInteger m1_order_rand;
    NSInteger m1_page;
    BOOL m1_isLogin;
}

@property (nonatomic, strong) UIView *m1_navView;

@property (nonatomic, strong) NSString *m1_max_time;

@property (nonatomic, copy)  NSDictionary *m1_params;

@property (nonatomic, strong) M1DragContainer *m1_container;

@property (nonatomic, strong)  NSMutableArray *m1_requestIndexs;

@property (nonatomic, strong) UIView *m1_empty;

@property (nonatomic, strong) UIView *m1_guidePageView;

@end

@implementation M1HomeViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    if (![M1User user]) {
        m1_isLogin = NO;
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _m1_requestIndexs = [NSMutableArray arrayWithCapacity:0];
    
    self.m1_hiddenNav = YES;
    
    self.m1_listData = [NSMutableArray arrayWithCapacity:0];
    
    [self m1_createEmptyView];
    
    [self m1_createNav];
    
    [self m1_loadUI];
    
    [self m1_reloadData];
    
    [self m1_requestData];
}

- (void)m1_leftAction:(UIButton *)sender{
    if (![M1User user]) {
        WEAKSELF
        [M1Alert m1_alertWithTitle:nil message:m1_loginText buttonTitles:@[@"取消", @"登录"] action:^(NSInteger index) {
            if (index == 1) {
                M1LoginVC *loginVC = [[M1LoginVC alloc] init];
                loginVC.m1_changeNavTitleColor = YES;
                loginVC.m1_changeBackImage = YES;
                loginVC.hidesBottomBarWhenPushed = YES;
                [weakSelf.navigationController pushViewController:loginVC animated:YES];
                
            }
        }];
        return;
    }
    
    M1FiltrateVC *filtrateVC = [[M1FiltrateVC alloc] init];
    filtrateVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:filtrateVC animated:YES];
    
    WEAKSELF
    filtrateVC.m1_requestBlock = ^(NSDictionary *m1_params) {
        [weakSelf m1_reloadData];
        weakSelf.m1_params = m1_params;
        
        [weakSelf m1_requestData];
    };
}



- (void) m1_requestData{
    
    
    if (![M1User user] &&self.m1_listData.count >=30) {
        return;
    }
    
    NSMutableDictionary *params = [@{@"page":@(m1_page), @"max_time":self.m1_max_time, @"order_rand":@(m1_order_rand)} mutableCopy];
    
    if ([_m1_params allKeys].count >0) {
        [params addEntriesFromDictionary:_m1_params];
    }
    
    WEAKSELF
    [M1HttpNet requestWithMethod:[M1User user]?
               m1_super_list_url:m1_recommendedlist_url params:params success:^(id resDic, NSInteger code, NSString *message) {
                   weakSelf.m1_max_time = [resDic m1_stringKey:@"max_time"];
                   if (weakSelf.m1_listData.count > 0) {
                       [weakSelf.m1_listData addObjectsFromArray:resDic[@"user"]];
                   }else{
                       if (![[NSUserDefaults standardUserDefaults] objectForKey:@"guidePage"] && [M1User user]) {
                           dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                               [[NSUserDefaults standardUserDefaults] setObject:@"YES" forKey:@"guidePage"];
                               [weakSelf m1_guidePageUI];
                           });
                       }
                       [weakSelf.m1_listData addObjectsFromArray:resDic[@"user"]];
                       [weakSelf.m1_container reloadData];
                   }
                   if ([weakSelf.m1_listData count] == 0 ) {
                       weakSelf.m1_empty.hidden = NO;
                   }else{
                       weakSelf.m1_empty.hidden = YES;
                   }
               } fail:^(id resDic, NSInteger code, NSString *message) {
                   
                   
               } showAni:weakSelf.m1_listData.count ==0?YES:NO];
}

#pragma mark - CCDraggableContainer DataSource
- (M1DragCardView *)draggableContainer:(M1DragContainer *)draggableContainer viewForIndex:(NSInteger)index {
    
    
    M1CustomCardView *cardView = [[M1CustomCardView alloc] initWithFrame:draggableContainer.bounds];
    
    cardView.m1_viewController = self;
    
    M1HomeModel *model = [M1HomeModel mj_objectWithKeyValues:[self.m1_listData objectAtIndex:index]];
    
    [cardView installData:model];
    
    if (index == self.m1_listData.count-7 ||index == self.m1_listData.count-1) {
        
        if ([_m1_requestIndexs indexOfObject:@(index)]!=NSNotFound) {
        }else{
            m1_page++;
            if (m1_order_rand == 5) {
                m1_order_rand = 1;
            }else{
                m1_order_rand++;
            }
            [_m1_requestIndexs addObject:@(index)];
            [self m1_requestData];
        }
    }
    
    return cardView;
}

- (NSInteger)numberOfIndexs {
    return self.m1_listData.count;
}

#pragma mark - CCDraggableContainer Delegate
- (void)draggableContainer:(M1DragContainer *)draggableContainer draggableDirection:(CCDraggableDirection)draggableDirection currentCardsCount:(NSInteger)currentCardsCount didRemoveView:(BOOL)didRemoveView{
    M1CustomCardView *view = self.m1_container.currentCards.firstObject;
    if (draggableDirection == CCDraggableDirectionLeft) {
        
    }
    
    if (draggableDirection == CCDraggableDirectionRight && [M1User user]) {
        NSInteger m1_index = view.tag;
        if (view.tag<=0) {
            m1_index = self.m1_listData.count-1;
        }
        M1HomeModel *model = [M1HomeModel mj_objectWithKeyValues:[self.m1_listData objectAtIndex:m1_index]];
        WEAKSELF
        [M1HttpNet requestWithMethod:m1_user_like_url params:@{@"to_uid":model.basic.uid} success:^(id resDic, NSInteger code, NSString *message) {
        } fail:^(id resDic, NSInteger code, NSString *message) {
            if (code == -20001 || code == -20003 || code==-20002) {
                [M1Alert m1_alertWithTitle:nil message:message buttonTitles:@[@"取消", @"立即完善"] action:^(NSInteger index) {
                    if (index == 1) {
                        if ([[M1User user].basic.avatar.img.url length] <= 0||[M1User user].basic.photos.count<=0) {
                            M1PhotoGalleryVC *photoVC = [[M1PhotoGalleryVC alloc] init];
                            photoVC.hidesBottomBarWhenPushed = YES;
                            [weakSelf.navigationController pushViewController:photoVC animated:YES];
                        }else{
                            M1PersonalDataVC *dataVC = [[M1PersonalDataVC alloc] init];
                            dataVC.hidesBottomBarWhenPushed = YES;
                            [weakSelf.navigationController pushViewController:dataVC animated:YES];
                        }
                    }
                }];
            }else if (code >-20000 &&code<=-10000){
                [M1Alert m1_alertWithTitle:nil message:message buttonTitles:@[@"取消", @"前往"] action:^(NSInteger index) {
                    //会员
                    
                    M1VIPCenterVC *m1_vipVC = [[M1VIPCenterVC alloc]init];
                    m1_vipVC.hidesBottomBarWhenPushed = YES;
                    [weakSelf.navigationController pushViewController:m1_vipVC animated:YES];
                    
                }];
            }
        } showAni:NO];
    }
    
    if (view.tag<=0&&[M1User user]) {
        self.m1_empty.hidden = NO;
        [M1Alert m1_alertWithTitle:nil message:@"没有更多数据了" buttonTitles:@[@"确定"] action:^(NSInteger index) {
            
        }];
    }
    
    if (view.tag<=0&&![M1User user]) {
        
        [draggableContainer reloadData];
        WEAKSELF
        [M1Alert m1_alertWithTitle:nil message:@"查看更多优质单身用户，请先注册账号。" buttonTitles:@[@"取消", @"登录"] action:^(NSInteger index) {
            if (index == 1) {
                M1LoginVC *loginVC = [[M1LoginVC alloc] init];
                loginVC.m1_changeNavTitleColor = YES;
                loginVC.m1_changeBackImage = YES;
                loginVC.hidesBottomBarWhenPushed = YES;
                [weakSelf.navigationController pushViewController:loginVC animated:YES];
            }
        }];
    }
}

- (void)draggableContainer:(M1DragContainer *)draggableContainer cardView:(M1DragCardView *)cardView didSelectIndex:(NSInteger)didSelectIndex {
    
    M1HomeModel *model = [M1HomeModel mj_objectWithKeyValues:[self.m1_listData objectAtIndex:didSelectIndex]];
    
    M1HomeDetailsVC *detailsVC = [[M1HomeDetailsVC alloc] initWithStyle:UITableViewStyleGrouped];
    detailsVC.m1_model = model;
    detailsVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailsVC animated:YES];
    
    M1CustomCardView *view = self.m1_container.currentCards.firstObject;
    
    detailsVC.m1_superLikeBlock = ^{
        [view.m1_loveBtn setImage:LOAD_LOCAL_IMG(@"home_icon_superLike") forState:UIControlStateNormal];
    };
}

- (void)draggableContainer:(M1DragContainer *)draggableContainer draggableDirection:(CCDraggableDirection)draggableDirection widthRatio:(CGFloat)widthRatio heightRatio:(CGFloat)heightRatio {
    if (draggableDirection == CCDraggableDirectionLeft) {
        
    }
    
    if (draggableDirection == CCDraggableDirectionRight) {
        
    }
}

- (void)draggableContainer:(M1DragContainer *)draggableContainer finishedDraggableLastCard:(BOOL)finishedDraggableLastCard {
    
}

- (void)m1_loadUI{
    self.m1_container = [[M1DragContainer alloc] initWithFrame:CGRectMake(iPhone4?25:15, 20 + (SCREENHEIGHT - m1_NAV_HEIGHT - (iPhone4?380:(iPhone5?430:530))) / 2, iPhone4?(SCREENWIDTH - 50):(SCREENWIDTH - 30), iPhone4?380:(iPhone5?430:530)) style:CCDraggableStyleUpOverlay];
    self.m1_container.delegate = self;
    self.m1_container.dataSource = self;
    [self.view addSubview:self.m1_container];
}

- (void) m1_reloadData{
    m1_page = 1;
    m1_order_rand = 1;
    self.m1_max_time = @"0";
    [self.m1_requestIndexs removeAllObjects];
    [self.m1_listData removeAllObjects];
}

- (void) m1_createNav{
    self.m1_navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 172)];
    [self.view addSubview:self.m1_navView];
    
    UIImageView *bgImage = [[UIImageView alloc] initWithFrame:CGRectZero];
    bgImage.image = LOAD_LOCAL_IMG(@"home_image_bgView");
    [_m1_navView addSubview:bgImage];
    
    [bgImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    UIImageView *title = [[UIImageView alloc] initWithFrame:CGRectZero];
    title.image = LOAD_LOCAL_IMG(@"home_icon_title");
    [_m1_navView addSubview:title];
    
    [title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(STATUS_HEIGHT + 10);
        make.centerX.equalTo(self.m1_navView.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(53, 16));
    }];
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [leftBtn setImage:LOAD_LOCAL_IMG(@"home_icon_screen") forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(m1_leftAction:) forControlEvents:UIControlEventTouchUpInside];
    [_m1_navView addSubview:leftBtn];
    
    [leftBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.centerY.equalTo(title.mas_centerY);
        make.size.mas_equalTo(CGSizeMake(47, 44));
    }];
    

}

- (void)m1_createEmptyView{
    self.m1_empty = [[UIView alloc] init];
    _m1_empty.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_m1_empty];
    _m1_empty.hidden = YES;
    
    [_m1_empty mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    UIImageView *image = [[UIImageView alloc] init];
    image.image = LOAD_LOCAL_IMG(@"data_none");
    [_m1_empty addSubview:image];
    
    [image mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view.mas_centerY);
        make.centerX.equalTo(self.view.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(100, 100));
    }];
    
    UILabel *title = [[UILabel alloc] init];
    title.text = @"空空如也~";
    title.textColor = m1_color(0x666666);
    title.font = m1_font(15);
    [_m1_empty addSubview:title];
    
    [title mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(image.mas_bottom).offset(10);
        make.centerX.equalTo(self.view.mas_centerX);
    }];
}


- (void) m1_guidePageUI{
    self.m1_guidePageView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _m1_guidePageView.backgroundColor = [m1_color(0x000000) colorWithAlphaComponent:0.6];
    [[UIApplication sharedApplication].keyWindow addSubview:_m1_guidePageView];
    
    UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, iPhone5?210:SCREENHEIGHT / 2, SCREENWIDTH, 215)];
    image.image = LOAD_LOCAL_IMG(@"home_guide_page");
    image.contentMode = UIViewContentModeScaleAspectFit;
    [_m1_guidePageView addSubview:image];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(m1_removeAction:)];
    [_m1_guidePageView addGestureRecognizer:tap];
}

- (void)m1_removeAction:(UITapGestureRecognizer *)tap{
    [self.m1_guidePageView removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
